﻿using System;
using System.Collections.Generic;
using System.IO;
using ZQNB.Common.Encrypt;
using ZQNB.Common.Serialize;

namespace ZQNB.Common.License
{
    public class MyPrivateLicenseHelper
    {
        //读取所有的私钥文件
        public static List<XmlKeyFileInfo> ReadAllPrivateKeys(string path, string searchPattern, SearchOption searchOption)
        {
            List<XmlKeyFileInfo> list = new List<XmlKeyFileInfo>();
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException("存放私钥的目录路径不能为空");
            }

            if (!Directory.Exists(path))
            {
                throw new ArgumentException(string.Format("存放私钥的目录没有{0}找到", path));
            }

            List<string> filePathList = MyIOHelper.GetFiles(path, searchPattern, SearchOption.AllDirectories);
            if (filePathList == null || filePathList.Count == 0)
            {
                return list;
            }

            foreach (string filePath in filePathList)
            {
                try
                {
                    string key = MyIOHelper.ReadAllText(filePath);
                    XmlKeyFileInfo keyFileInfo = new XmlKeyFileInfo();
                    keyFileInfo.KeyValue = key;
                    keyFileInfo.LicenseBy = Path.GetFileNameWithoutExtension(filePath);
                    list.Add(keyFileInfo);
                }
                catch (Exception)
                {
                    //throw new ApplicationException("文件格式损坏");
                }

            }
            return list;
        }

        //用私钥对License加壳
        public static MyLicenseShell<T> AddShell<T>(T license, string xmlPrivateKey)
        {
            if (string.IsNullOrEmpty(xmlPrivateKey) || license == null)
            {
                //非法的参数
                return null;
            }

            string licenseValue = MySerializeXmlHelper.SerializeToXmlText<T>(license);
            MyLicenseShell<T> info = new MyLicenseShell<T>();

            //授权的签名
            string licenseSignature = MySignatureHelper.SignByPrivateKey(licenseValue, xmlPrivateKey);
            //厂商的签名
            string theMarkSignature = MySignatureHelper.SignByPrivateKey(Properties.Resources.SignatureMark, xmlPrivateKey);

            info.LicenseSignature = licenseSignature;
            info.TheMarkSignature = theMarkSignature;
            info.LicenseValue = license; //授权文件实例

            return info;
        }
    }
}
